package com.own.component.store.redis.method;

import com.own.component.store.core.method.StoreAtomic;
import org.redisson.api.RedissonClient;

import java.time.Duration;

/**
 * DefaultRedisStoreAtomic
 *
 * @author chenxueli
 * @date 2022-06-15 03:14:15
 */
public class DefaultRedisStoreAtomic extends DefaultBaseStoreMethod implements StoreAtomic {

    public DefaultRedisStoreAtomic(RedissonClient redissonClient) {
        super(redissonClient);
    }

    /**
     * 获取值
     *
     * @param key key
     * @return 值
     */
    @Override
    public long get(String key) {
        return getRedissonClient().getAtomicLong(buildKey(key)).get();
    }

    /**
     * 获取值
     *
     * @param key      key
     * @param duration 超时时间
     * @return 值
     */
    @Override
    public long get(String key, Duration duration) {
        var atomic = getRedissonClient().getAtomicLong(buildKey(key));
        var count = atomic.get();
        if (duration != null) {
            atomic.expire(duration);
        }
        return count;
    }

    /**
     * 获取值
     *
     * @param key key
     * @return 值
     */
    @Override
    public long getAndIncrement(String key) {
        return getRedissonClient().getAtomicLong(buildKey(key)).getAndIncrement();
    }

    /**
     * 获取值
     *
     * @param key      key
     * @param duration 超时时间
     * @return 值
     */
    @Override
    public long getAndIncrement(String key, Duration duration) {
        var atomic = getRedissonClient().getAtomicLong(buildKey(key));
        var count = atomic.getAndIncrement();
        if (duration != null) {
            atomic.expire(duration);
        }
        return count;
    }

    /**
     * 获取值
     *
     * @param key key
     * @return 值
     */
    @Override
    public long incrementAndGet(String key) {
        return getRedissonClient().getAtomicLong(buildKey(key)).incrementAndGet();
    }

    /**
     * 获取原子值
     *
     * @param key      key
     * @param duration 超时时间
     * @return 值
     */
    @Override
    public long incrementAndGet(String key, Duration duration) {
        var atomic = getRedissonClient().getAtomicLong(buildKey(key));
        var count = atomic.incrementAndGet();
        if (duration != null) {
            atomic.expire(duration);
        }
        return count;
    }

}
